package org.example.registry.etcd;

import cn.hutool.json.JSONUtil;
import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.KV;
import io.etcd.jetcd.Lease;
import io.etcd.jetcd.options.PutOption;
import org.example.Model.ServiceMetaInfo;
import org.example.config.RegistryConfig;
import org.example.registry.IRegistry;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;

/**
 * @Author Jiangxiaonan
 * @Description
 * @Date 2024/9/12 21:23
 **/
public class EtcdRegistry implements IRegistry {

    private Client client;

    private KV kvClient;

    // 根节点
    private static final String ROOT = "/rpc/";

    @Override
    public void init(RegistryConfig config) {
        client = Client.builder().endpoints(config.getAddress()).connectTimeout(Duration.ofMillis(config.getTimeout())).build();
        kvClient = client.getKVClient();
    }

    @Override
    public void register(ServiceMetaInfo serviceMetaInfo) throws Exception {
        // 创建Lease和KV客户端
        Lease leaseClient = client.getLeaseClient();
        // 创建一个30秒的租约
        long leaseId = leaseClient.grant(30).get().getID();
        // 创建一个KV存储节点
        String registerKey = ROOT + serviceMetaInfo.getServiceNodeKey();
        ByteSequence key = ByteSequence.from(registerKey, StandardCharsets.UTF_8);
        ByteSequence value = ByteSequence.from(JSONUtil.toJsonStr(serviceMetaInfo), StandardCharsets.UTF_8);

        // 设置过期时间
        PutOption putOption = PutOption.builder().withLeaseId(leaseId).build();
        // 写入KV存储
        kvClient.put(key, value, putOption).get();
    }

    @Override
    public void deregister(ServiceMetaInfo serviceMetaInfo) {

    }

    @Override
    public List<ServiceMetaInfo> discovery(String serviceKey) {
        return null;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void heartbeat() {

    }
}
